package com.dongjiantong.web.protal.controller.quarantine;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.service.EarMarkLifeReadeService;
import com.dongjiantong.biz.service.EarMarkLifeWriteService;
import com.dongjiantong.biz.service.EarMarksWriteService;
import com.dongjiantong.biz.service.FarmStockService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.service.FarmRecordsProductionService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.quarantine.enums.DjtBreedReportsStatus;
import com.dongjiantong.quarantine.model.DjtBreedReports;
import com.dongjiantong.quarantine.serviceImpl.*;
import com.dongjiantong.user.enums.OrgTypeEnum;
import com.dongjiantong.user.model.Farms;
import com.dongjiantong.user.service.FarmsService;
import com.dongjiantong.user.service.OrganizationService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMethod;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by mz on 8/1/18.
 */
@Slf4j
@OpenBean
public class DjtBreedReportsWebController {

    @Reference(version = "1.0.0")
    private DjtBreedReportsReadService djtBreedReportsReadService;

    @Reference(version = "1.0.0")
    private DjtBreedReportsWriteService djtBreedReportsWriteService;

    @Reference(version = "1.0.0")
    private BreedReportsFileReadService breedReportsFileReadService;

    @Reference(version = "1.0.0")
    private DjtButcherAdmissionInspectionsReadService djtButcherAdmissionInspectionsReadService;

    @Reference(version = "1.0.0")
    private DjtButcherAdmissionInspectionsWriteService djtButcherAdmissionInspectionsWriteService;

    @Reference(version = "1.0.0")
    private DjtButcherReportsReadService djtButcherReportsReadService;

    @Reference(version = "1.0.0")
    private DjtButcherReportsWriteService djtButcherReportsWriteService;

    @Reference(version = "1.0.0")
    private HarmlessReadService harmlessReadService;

    @Reference(version = "1.0.0")
    private HarmlessWriteService harmlessWriteService;

    @Reference(version = "1.0.0")
    private FarmRecordsProductionService farmRecordsProductionService;

    @Reference(version = "1.0.0")
    private FarmStockService farmStockService;

    @Reference(version = "1.0.0")
    private FarmsService farmsService;

    @Reference(version = "1.0.0")
    private EarMarkLifeReadeService earMarkLifeReadeService;

    @Reference(version = "1.0.0")
    private EarMarkLifeWriteService earMarkLifeWriteService;

    @Reference(version = "1.0.0")
    private EarMarksWriteService earMarksWriteService;

    @Reference(version = "1.0.0")
    private OrganizationService organizationService;

    /**
     * 查询单据详情 根据 单据 ID
     *
     * @param id 主键 ID
     * @return Response<DjtBreedReports>
     */
    @OpenMethod(
            key = "web.find.breed.report.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public Response<DjtBreedReports> findById(Long id) {
        if (id == null) {
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(), HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }

        try {
            DjtBreedReports djtBreedReports = djtBreedReportsReadService.findById(id);
            Map<String, Object> map = Maps.newHashMap();
            map.put("field", "site_survey_photo_list");
            map.put("type1", ReportType.QUARANTINE_ORIGIN_AREA.value());
            map.put("type2", 1);
            map.put("relevanceId", djtBreedReports.getId());
            List<String> site_survey_photo_list = breedReportsFileReadService.findListByType(map);
            djtBreedReports.setSite_survey_photo_list(site_survey_photo_list);
            map.put("field", "quarantine_cert_photo_list");
            List<String> quarantine_cert_photo_list = breedReportsFileReadService.findListByType(map);
            djtBreedReports.setQuarantine_cert_photo_list(quarantine_cert_photo_list);
            map.clear();
            map.put("reportId", id);
            map.put("reportType", ReportType.QUARANTINE_ORIGIN_AREA.value());
            List<String> ear_tag_numbers = earMarkLifeReadeService.findListByBreedReportId(map);
            djtBreedReports.setEar_tag_numbers(ear_tag_numbers);
            return Response.ok(djtBreedReports);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    /**
     * 查询产地检疫列表
     *
     * @param pageNum   页码
     * @param pageSize  条数
     * @param startDate 从日期
     * @param endDate   到日期
     * @param areaList  地区
     * @param breedType 动物类型
     * @param status    单据状态
     * @return Response<PageInfo<DjtBreedReports>>
     */
    @OpenMethod(
            key = "web.paging.breed.report",
            paramNames = {"pageNum", "pageSize", "startDate", "endDate", "areaList", "breedType", "status"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtBreedReports>> pagingBreedReportForWeb(Integer pageNum,
                                                                       Integer pageSize,
                                                                       String startDate,
                                                                       String endDate,
                                                                       List<Integer> areaList,
                                                                       List<Integer> breedType,
                                                                       Integer status) {
        try {
            List<Long> orgIds = new ArrayList<>();
            orgIds.add(-1L);
            if (areaList == null || areaList.isEmpty()) {
                LoginInfo loginInfo = UserUtil.getCurrentUser();
                List<Map<String, Object>> org = organizationService.findByUserId(loginInfo.getId());
                for (Map<String, Object> map : org)
                    if (map.get("org_type").equals(OrgTypeEnum.OrgType_declaration.getCode())
                            || map.get("org_type").equals(OrgTypeEnum.OrgType_cert.getCode()))
                        orgIds.add((Long) map.get("id"));
            } else {
                Map<String, Object> map = Maps.newHashMap();
                int i = 0;
                for (Integer areaCode : areaList) {
                    if (i == 0) {
                        map.put("province_id", areaCode);
                    } else if (i == 1) {
                        map.put("city_id", areaCode);
                    } else if (i == 2) {
                        map.put("region_id", areaCode);
                    } else if (i == 3) {
                        map.put("street_id", areaCode);
                    }
                    i++;
                }
                List<Map<String, Object>> org = organizationService.findByArea(map);
                for (Map<String, Object> map1 : org)
                    if (map.get("org_type").equals(OrgTypeEnum.OrgType_declaration.getCode())
                            || map.get("org_type").equals(OrgTypeEnum.OrgType_cert.getCode()))
                        orgIds.add((Long) map.get("id"));
            }
            Map<String, Object> map = Maps.newHashMap();
            map.put("orgIds", orgIds);
            if (!Strings.isNullOrEmpty(startDate)) {
                Date startDate1 = new Date(Long.valueOf(startDate));
                map.put("start", startDate1);
            }
            if (!Strings.isNullOrEmpty(endDate)) {
                Date endDate1 = new Date(Long.valueOf(endDate) + 86400000);
                map.put("end", endDate1);
            }
            if (breedType.size() > 0) {
                switch (breedType.size()) {
                    case 1:
                        map.put("breedType", breedType.get(0));
                        break;
                    case 2:
                        map.put("breedSecondType", breedType.get(1));
                        break;
                    case 3:
                        map.put("breedThirdType", breedType.get(2));
                    default:
                        break;
                }
            }

            if (status != null) map.put("status", status);

            map.put("deleteFlag", 1);
            PageInfo<DjtBreedReports> djtBreedReportsPageInfo = djtBreedReportsReadService.pagingForWeb(pageNum, pageSize, map);
            for (DjtBreedReports djtBreedReports : djtBreedReportsPageInfo.getList()) {
                map.clear();
                map.put("field", "site_survey_photo_list");
                map.put("type1", ReportType.QUARANTINE_ORIGIN_AREA.value());
                map.put("type2", 1);
                map.put("relevanceId", djtBreedReports.getId());
                List<String> site_survey_photo_list = breedReportsFileReadService.findListByType(map);
                djtBreedReports.setSite_survey_photo_list(site_survey_photo_list);
                map.put("field", "quarantine_cert_photo_list");
                List<String> quarantine_cert_photo_list = breedReportsFileReadService.findListByType(map);
                djtBreedReports.setQuarantine_cert_photo_list(quarantine_cert_photo_list);
                map.clear();
                map.put("reportId", djtBreedReports.getId());
                map.put("reportType", ReportType.QUARANTINE_ORIGIN_AREA.value());
                List<String> ear_tag_numbers = earMarkLifeReadeService.findListByBreedReportId(map);
                djtBreedReports.setEar_tag_numbers(ear_tag_numbers);
            }
            return Response.ok(djtBreedReportsPageInfo);
        } catch (Exception e) {
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }

    }


    @OpenMethod(
            key = "web.paging.breed.report.for.ab.cert",
            paramNames = {"pageNum", "pageSize", "startDate", "endDate", "startAdd", "toAdd", "status", "number", "owner", "certNumber", "isAOrB","deleteFlag"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtBreedReports>> pagingBreedReportForABCert(Integer pageNum,
                                                                          Integer pageSize,
                                                                          String startDate,
                                                                          String endDate,
                                                                          String startAdd,
                                                                          String toAdd,
                                                                          Integer status,
                                                                          String number,
                                                                          String owner,
                                                                          String certNumber,
                                                                          Integer isAOrB,
                                                                          Integer deleteFlag) {
        try {
            List<Long> orgIds = new ArrayList<>();
            orgIds.add(-1L);
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            List<Map<String, Object>> org = organizationService.findByUserId(loginInfo.getId());
            for (Map<String, Object> map : org)
                if (map.get("org_type").equals(OrgTypeEnum.OrgType_declaration.getCode())
                        || map.get("org_type").equals(OrgTypeEnum.OrgType_cert.getCode()))
                    orgIds.add((Long) map.get("id"));
            Map<String, Object> map = Maps.newHashMap();
            map.put("orgIds", orgIds);
            if (!Strings.isNullOrEmpty(startDate)) {
                Date startDate1 = new Date(Long.valueOf(startDate));
                map.put("start", startDate1);
            }
            if (!Strings.isNullOrEmpty(endDate)) {
                Date endDate1 = new Date(Long.valueOf(endDate) + 86400000);
                map.put("end", endDate1);
            }
            if (status != null) map.put("status", status);
            if (deleteFlag != null) map.put("deleteFlag", deleteFlag);
            else map.put("deleteFlag", 1);
            if (!Strings.isNullOrEmpty(number)) map.put("number", number);
            if (!Strings.isNullOrEmpty(owner)) map.put("owner", owner);
            if (!Strings.isNullOrEmpty(certNumber)) map.put("certNumber", certNumber);
            if (!Strings.isNullOrEmpty(startAdd)) map.put("startAdd",startAdd);
            if (!Strings.isNullOrEmpty(toAdd)) map.put("toAdd",toAdd);
            List<Integer> isToLocals = new ArrayList<>();

            if (isAOrB != null) {
                if (isAOrB == -1) {
                    isToLocals.add(-1);
                    map.put("isToLocals", isToLocals);
                } else {
                    isToLocals.add(1);
                    isToLocals.add(2);
                    map.put("isToLocals", isToLocals);
                }
            }
            PageInfo<DjtBreedReports> djtBreedReportsPageInfo = djtBreedReportsReadService.pagingForWeb(pageNum, pageSize, map);
            for (DjtBreedReports djtBreedReports : djtBreedReportsPageInfo.getList()) {
                map.clear();
                map.put("field", "site_survey_photo_list");
                map.put("type1", ReportType.QUARANTINE_ORIGIN_AREA.value());
                map.put("type2", 1);
                map.put("relevanceId", djtBreedReports.getId());
                List<String> site_survey_photo_list = breedReportsFileReadService.findListByType(map);
                djtBreedReports.setSite_survey_photo_list(site_survey_photo_list);
                map.put("field", "quarantine_cert_photo_list");
                List<String> quarantine_cert_photo_list = breedReportsFileReadService.findListByType(map);
                djtBreedReports.setQuarantine_cert_photo_list(quarantine_cert_photo_list);
                map.clear();
                map.put("reportId", djtBreedReports.getId());
                map.put("reportType", ReportType.QUARANTINE_ORIGIN_AREA.value());
                List<String> ear_tag_numbers = earMarkLifeReadeService.findListByBreedReportId(map);
                djtBreedReports.setEar_tag_numbers(ear_tag_numbers);
            }
            return Response.ok(djtBreedReportsPageInfo);
        } catch (Exception e) {
            return Response.fail(e.getMessage());
        }
    }


    @OpenMethod(
            key = "web.get.a.or.b.cert.sum",
            paramNames = {"startDate","endDate","breedType","isAOrB","isDeliverOrReceive"},
            httpMethods = RequestMethod.GET
    )
    public Response<List<Map<String , Object>>> getABCertSum(String startDate,
                                                             String endDate,
                                                             List<Integer> breedType,
                                                             Integer isAOrB,
                                                             Integer isDeliverOrReceive){

        try{
            Map<String, Object> map = Maps.newHashMap();
            List<Long> orgIds = new ArrayList<>();
            orgIds.add(-1L);
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            List<Map<String, Object>> org = organizationService.findByUserId(loginInfo.getId());
            for (Map<String, Object> orgMap : org)
                if (orgMap.get("org_type").equals(OrgTypeEnum.OrgType_declaration.getCode())
                        || orgMap.get("org_type").equals(OrgTypeEnum.OrgType_cert.getCode()))
                    orgIds.add((Long) orgMap.get("id"));

            map.put("orgIds", orgIds);

            if (breedType.size() > 0) {
                switch (breedType.size()) {
                    case 1:
                        map.put("breedType", breedType.get(0));
                        break;
                    case 2:
                        map.put("breedSecondType", breedType.get(1));
                        break;
                    case 3:
                        map.put("breedThirdType", breedType.get(2));
                    default:
                        break;
                }
            }else {
                map.put("breedSecondType", 101);
            }
            if (!Strings.isNullOrEmpty(startDate)) {
                Date startDate1 = new Date(Long.valueOf(startDate));
                map.put("start", startDate1);
            }
            if (!Strings.isNullOrEmpty(endDate)) {
                Date endDate1 = new Date(Long.valueOf(endDate) + 86400000);
                map.put("end", endDate1);
            }
//            if (!Strings.isNullOrEmpty(startAdd)) map.put("startAdd",startAdd);
//            if (!Strings.isNullOrEmpty(toAdd)) map.put("toAdd",toAdd);
            List<Integer> isToLocals = new ArrayList<>();
            if (isAOrB != null) {
                if (isAOrB == -1) {
                    isToLocals.add(-1);
                    map.put("isToLocals", isToLocals);
                } else {
                    isToLocals.add(1);
                    isToLocals.add(2);
                    map.put("isToLocals", isToLocals);
                }
            }

            if(isDeliverOrReceive != null){
                if(isDeliverOrReceive == -1){
                    List<Map<String , Object>> result = djtBreedReportsReadService.sumGroupByReceive(map);
                    return Response.ok(result);
                }else {
                    List<Map<String , Object>> result = djtBreedReportsReadService.sumGroupByDeliver(map);
                    return Response.ok(result);
                }
            }else {
                List<Map<String , Object>> result = djtBreedReportsReadService.sumGroupByDeliver(map);
                return Response.ok(result);
            }

        }catch (Exception e){
           return Response.fail(e.getMessage());
        }
    }

    /**
     * 产地检疫删除操作
     *
     * @param id 单据id
     * @return Response<Boolean>
     */
    @OpenMethod(
            key = "web.delete.breed.report.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.POST
    )
    @Transactional
    public Response<Boolean> deleteById(Long id) {
        if (id == null) {
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(), HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }
        try {
            Integer status = djtBreedReportsReadService.findStatusById(id);
            djtBreedReportsWriteService.updateDeleteFlag(id);
            Map<String, Object> map = Maps.newHashMap();
            map.put("reportId", id);
            map.put("reportType", ReportType.QUARANTINE_ORIGIN_AREA.value());
            List<String> ear_tag_numbers = earMarkLifeReadeService.findListByBreedReportId(map);
            if (ear_tag_numbers != null && !ear_tag_numbers.isEmpty()) {
                earMarksWriteService.updateMarks(clearEarIsSelectedParam(ear_tag_numbers));
            }
            earMarkLifeWriteService.deleteByReportIdAndType(getParamMapOfEarLifeQuery(id, ReportType.QUARANTINE_ORIGIN_AREA.value()));
            if (status.equals(DjtBreedReportsStatus.HAS_LICENSE.value())) {
                harmlessWriteService.updateDeleteFlag(getUpdateHarmlessParamMap(id, ReportType.QUARANTINE_ORIGIN_AREA.value()));
                //todo or not do delete breed report form
                Long admissionId = djtButcherAdmissionInspectionsReadService.checkIsExist(id);
                if (admissionId != null) {
                    djtButcherAdmissionInspectionsWriteService.updateDeleteFlag(admissionId);
                    earMarkLifeWriteService.deleteByReportIdAndType(getParamMapOfEarLifeQuery(admissionId, ReportType.ADMISSION_INSPECTION.value()));
                    harmlessWriteService.updateDeleteFlag(getUpdateHarmlessParamMap(id, ReportType.ADMISSION_INSPECTION.value()));
                }
                Long butcherId = djtButcherReportsReadService.checkIsExist(admissionId);
                if (butcherId != null) {
                    djtButcherReportsWriteService.updateDeleteFlag(butcherId);
                    //todo or not do delete butcher report form
                    earMarkLifeWriteService.deleteByReportIdAndType(getParamMapOfEarLifeQuery(admissionId, ReportType.ANEMOMETER_INSPECTION.value()));
                    earMarkLifeWriteService.deleteByReportIdAndType(getParamMapOfEarLifeQuery(admissionId, ReportType.SYNCHRONOUS_INSPECTION.value()));
                    harmlessWriteService.updateDeleteFlag(getUpdateHarmlessParamMap(id, ReportType.SYNCHRONOUS_INSPECTION.value()));
                    harmlessWriteService.updateDeleteFlag(getUpdateHarmlessParamMap(id, ReportType.ANEMOMETER_INSPECTION.value()));
                }
                farmRecordsProductionService.updateDeleteFlagByReportIdAndReportType(getParamMapOfUpdateProduction(id, ReportType.QUARANTINE_ORIGIN_AREA.value()));
                farmStockService.updateByFarmId(getStockUpdateParamsMap(id));

            }
            return Response.ok(Boolean.TRUE);
        } catch (Exception e) {
            return Response.fail(HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }


    @OpenMethod(
            key = "apply.top.10.by.area",
            httpMethods = RequestMethod.GET
    )
    public Response<List<Map<String, Object>>> applyTop10ByArea() {

        try {
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            List<Long> farmsIds = new ArrayList<>();
            List<Farms> farmsList = farmsService.selectByUserId(loginInfo.getId());
            for (Farms farms : farmsList) farmsIds.add(farms.getId());
            Map<String, Object> map = Maps.newHashMap();
            map.put("farmsIds", farmsIds);
            map.put("deleteFlag", 1);
            List<Map<String, Object>> result = djtBreedReportsReadService.applyTop10ByArea(map);
            if (result.size() <= 10) return Response.ok(result);
            else {
                List<Map<String, Object>> resultList = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    resultList.add(result.get(i));
                }
                return Response.ok(resultList);
            }
        } catch (Exception e) {
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @OpenMethod(
            key = "apply.top.10.by.station",
            httpMethods = RequestMethod.GET
    )
    public Response<List<Map<String, Object>>> applyTop10ByApplyStation() {

        try {
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            List<Long> farmsIds = new ArrayList<>();
            List<Farms> farmsList = farmsService.selectByUserId(loginInfo.getId());
            for (Farms farms : farmsList) farmsIds.add(farms.getId());
            Map<String, Object> map = Maps.newHashMap();
            map.put("farmsIds", farmsIds);
            map.put("deleteFlag", 1);
            List<Map<String, Object>> result = djtBreedReportsReadService.applyTop10ByApplyStation(map);
            if (result.size() <= 10) return Response.ok(result);
            else {
                List<Map<String, Object>> resultList = new ArrayList<>();
                for (int i = 0; i < 10; i++) {
                    resultList.add(result.get(i));
                }
                return Response.ok(resultList);
            }
        } catch (Exception e) {
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    @OpenMethod(
            key = "web.get.sum.by.is.to.local",
            paramNames = {"startDate", "endDate", "areaList", "breedType"},
            httpMethods = RequestMethod.GET
    )
    public Response<Map<String, Object>> getIsToLocal(String startDate,
                                                      String endDate,
                                                      List<Integer> areaList,
                                                      List<Integer> breedType) {

        try {
            List<Long> farmsIds = new ArrayList<>();
            farmsIds.add(-1L);
            if (areaList == null || areaList.isEmpty()) {
                LoginInfo loginInfo = UserUtil.getCurrentUser();
                List<Farms> farmsList = farmsService.selectByUserId(loginInfo.getId());
                for (Farms farms : farmsList) farmsIds.add(farms.getId());
            } else {
                Map<String, Object> map = Maps.newHashMap();
                int i = 0;
                for (Integer areaCode : areaList) {
                    if (i == 0) {
                        map.put("province_id", areaCode);
                    } else if (i == 1) {
                        map.put("city_id", areaCode);
                    } else if (i == 2) {
                        map.put("region_id", areaCode);
                    } else if (i == 3) {
                        map.put("street_id", areaCode);
                    }
                    i++;
                }
                List<Farms> farmsList = farmsService.selectByMap(map);
                for (Farms farms : farmsList) farmsIds.add(farms.getId());
            }
            Map<String, Object> map = Maps.newHashMap();
            if (breedType.size() > 0) {
                switch (breedType.size()) {
                    case 1:
                        map.put("breedType", breedType.get(0));
                        break;
                    case 2:
                        map.put("breedSecondType", breedType.get(1));
                        break;
                    case 3:
                        map.put("breedThirdType", breedType.get(2));
                    default:
                        break;
                }
            }
            map.put("farmsIds", farmsIds);
            if (!Strings.isNullOrEmpty(startDate)) {
                Date startDate1 = new Date(Long.valueOf(startDate));
                map.put("start", startDate1);
            }
            if (!Strings.isNullOrEmpty(endDate)) {
                Date endDate1 = new Date(Long.valueOf(endDate) + 86400000);
                map.put("end", endDate1);
            }
            map.put("deleteFlag", 1);
            List<Map<String, Object>> resultPre = djtBreedReportsReadService.findSumByIsToLocal(map);
            Integer isLocal = 0;
            Integer noIsLocal = 0;
            for (Map<String, Object> map1 : resultPre) {
                if ((int) map1.get("isToLocal") == -1) {
                    noIsLocal += ((BigDecimal) map1.get("quantity")).intValue();
                } else {
                    isLocal += ((BigDecimal) map1.get("quantity")).intValue();
                }
            }
            Map<String, Object> resultMap = Maps.newHashMap();
            resultMap.put("isLocal", isLocal);
            resultMap.put("noIsLocal", noIsLocal);
            return Response.ok(resultMap);
        } catch (Exception e) {
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @OpenMethod(
            key = "web.get.quarantine.report.date.analtsis",
            paramNames = {"startDate", "endDate", "areaList", "breedType"},
            httpMethods = RequestMethod.GET
    )
    public Response<List<Map<String, Object>>> dataAnalysis(String startDate,
                                                            String endDate,
                                                            List<Integer> areaList,
                                                            List<Integer> breedType) {

        try {
            Map<String, Object> map = buildDataParamMap(areaList, breedType);
            BigDecimal defaultValue = new BigDecimal(0.00);
            Date today = new Date(DateFormat.getDateInstance().format(new Date()));
            //this year
            Long oneDay = 86400000L;
            Date start = !Strings.isNullOrEmpty(startDate) ? new Date(Long.valueOf(startDate)) : new Date(today.getTime() - oneDay);
            Date end = !Strings.isNullOrEmpty(endDate) ? new Date(Long.valueOf(endDate) + oneDay) : today;
            map.put("start", start);
            map.put("end", end);

            //is local
            List<Map<String, Object>> thisResultPre = djtBreedReportsReadService.findSumByIsToLocal(map);
            Double thisIsLocal = 0.00;
            Double thisNoIsLocal = 0.00;
            for (Map<String, Object> map1 : thisResultPre)
                if ((int) map1.get("isToLocal") == -1)
                    thisNoIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
                else thisIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
            Map<String, Object> thisYearOtherDataMap = djtBreedReportsReadService.findSumForWebDataAnalysis(map);
            Double thisCount = ((Long) thisYearOtherDataMap.get("count")).doubleValue();
            Double thisQuantity = ((BigDecimal) thisYearOtherDataMap.getOrDefault("quantity", defaultValue)).doubleValue();
            Double thisQualifiedQuantity = ((BigDecimal) thisYearOtherDataMap.getOrDefault("qualifiedQuantity", defaultValue)).doubleValue();
            Double thisUnqualifiedQuantity = ((BigDecimal) thisYearOtherDataMap.getOrDefault("unqualifiedQuantity", defaultValue)).doubleValue();

            //last year
            map.put("start", getLastYearThisTime(start));
            map.put("end", getLastYearThisTime(end));
            // is local
            List<Map<String, Object>> lastYearResultPre = djtBreedReportsReadService.findSumByIsToLocal(map);
            Double lastYearIsLocal = 0.00;
            Double lastYearNoIsLocal = 0.00;
            for (Map<String, Object> map1 : lastYearResultPre)
                if ((int) map1.get("isToLocal") == -1)
                    lastYearNoIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
                else lastYearIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
            Map<String, Object> lastYearOtherDataMap = djtBreedReportsReadService.findSumForWebDataAnalysis(map);
            Double lastYearCount = ((Long) lastYearOtherDataMap.get("count")).doubleValue();
            Double lastYearQuantity = ((BigDecimal) lastYearOtherDataMap.getOrDefault("quantity", defaultValue)).doubleValue();
            Double lastYearQualifiedQuantity = ((BigDecimal) lastYearOtherDataMap.getOrDefault("qualifiedQuantity", defaultValue)).doubleValue();
            Double lastYearUnqualifiedQuantity = ((BigDecimal) lastYearOtherDataMap.getOrDefault("unqualifiedQuantity", defaultValue)).doubleValue();

            //last month
            map.put("start", getLastMonthThisTime(start));
            map.put("end", getLastMonthThisTime(end));
            // is local
            List<Map<String, Object>> lastMonthResultPre = djtBreedReportsReadService.findSumByIsToLocal(map);
            Double lastMonthIsLocal = 0.00;
            Double lastMonthNoIsLocal = 0.00;
            for (Map<String, Object> map1 : lastMonthResultPre)
                if ((int) map1.get("isToLocal") == -1)
                    lastMonthIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
                else lastMonthNoIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();

            Map<String, Object> lastMonthOtherDataMap = djtBreedReportsReadService.findSumForWebDataAnalysis(map);
            Double lastMonthCount = ((Long) lastMonthOtherDataMap.get("count")).doubleValue();
            Double lastMonthQuantity = ((BigDecimal) lastMonthOtherDataMap.getOrDefault("quantity", defaultValue)).doubleValue();
            Double lastMonthQualifiedQuantity = ((BigDecimal) lastMonthOtherDataMap.getOrDefault("qualifiedQuantity", defaultValue)).doubleValue();
            Double lastMonthUnqualifiedQuantity = ((BigDecimal) lastMonthOtherDataMap.getOrDefault("unqualifiedQuantity", defaultValue)).doubleValue();

            //analysis data
            DecimalFormat df = new DecimalFormat("######0.00");
            String yoyCount = lastYearCount == 0.00 ? thisCount * 100 + "%" : df.format((thisCount / lastYearCount - 1) * 100) + "%";
            String yoyQuantity = lastYearQuantity == 0.00 ? thisQuantity * 100 + "%" : df.format((thisQuantity / lastYearQuantity - 1) * 100) + "%";
            String yoyQualifiedQuantity = lastYearQualifiedQuantity == 0.00 ? thisQualifiedQuantity * 100 + "%" : df.format((thisQualifiedQuantity / lastYearQualifiedQuantity - 1) * 100) + "%";
            String yoyUnqualifiedQuantity = lastYearUnqualifiedQuantity == 0.00 ? thisUnqualifiedQuantity * 100 + "%" : df.format((thisUnqualifiedQuantity / lastYearUnqualifiedQuantity - 1) * 100) + "%";
            String yoyIsLocal = lastYearIsLocal == 0.00 ? thisIsLocal * 100 + "%" : df.format((thisIsLocal / lastYearIsLocal - 1) * 100) + "%";
            String yoyNoIsLocal = lastYearNoIsLocal == 0.00 ? thisNoIsLocal * 100 + "%" : df.format((thisNoIsLocal / lastYearNoIsLocal - 1) * 100) + "%";

            String qoqCount = lastMonthCount == 0.00 ? thisCount * 100 + "%" : df.format((thisCount / lastMonthCount - 1) * 100) + "%";
            String qoqQuantity = lastMonthQuantity == 0.00 ? thisQuantity * 100 + "%" : df.format((thisQuantity / lastMonthQuantity - 1) * 100) + "%";
            String qoqQualifiedQuantity = lastMonthQualifiedQuantity == 0.00 ? thisQualifiedQuantity * 100 + "%" : df.format((thisQualifiedQuantity / lastMonthQualifiedQuantity - 1) * 100) + "%";
            String qoqUnqualifiedQuantity = lastMonthUnqualifiedQuantity == 0.00 ? thisUnqualifiedQuantity * 100 + "%" : df.format((thisUnqualifiedQuantity / lastMonthUnqualifiedQuantity - 1) * 100) + "%";
            String qoqIsLocal = lastMonthIsLocal == 0.00 ? thisIsLocal * 100 + "%" : df.format((thisIsLocal / lastMonthIsLocal - 1) * 100) + "%";
            String qoqNoIsLocal = lastMonthNoIsLocal == 0.00 ? thisNoIsLocal * 100 + "%" : df.format((thisNoIsLocal / lastMonthNoIsLocal - 1) * 100) + "%";

            List<Map<String, Object>> resultList = new ArrayList<>();
            Map<String, Object> resultMap = Maps.newHashMap();
            resultMap.put("name", "检疫申请数");
            resultMap.put("amount", thisCount);
            resultMap.put("yoy", yoyCount);
            resultMap.put("qoq", qoqCount);
            resultList.add(0, resultMap);
            Map<String, Object> resultMap2 = Maps.newHashMap();
            resultMap2.put("name", "动物申报数量");
            resultMap2.put("amount", thisQuantity);
            resultMap2.put("yoy", yoyQuantity);
            resultMap2.put("qoq", qoqQuantity);
            resultList.add(1, resultMap2);
            Map<String, Object> resultMap3 = Maps.newHashMap();
            resultMap3.put("name", "本地屠宰");
            resultMap3.put("amount", thisIsLocal);
            resultMap3.put("yoy", yoyIsLocal);
            resultMap3.put("qoq", qoqIsLocal);
            resultList.add(2, resultMap3);
            Map<String, Object> resultMap4 = Maps.newHashMap();
            resultMap4.put("name", "销往外地");
            resultMap4.put("amount", thisNoIsLocal);
            resultMap4.put("yoy", yoyNoIsLocal);
            resultMap4.put("qoq", qoqNoIsLocal);
            resultList.add(3, resultMap4);
            Map<String, Object> resultMap5 = Maps.newHashMap();
            resultMap5.put("name", "合格数");
            resultMap5.put("amount", thisQualifiedQuantity);
            resultMap5.put("yoy", yoyQualifiedQuantity);
            resultMap5.put("qoq", qoqQualifiedQuantity);
            resultList.add(4, resultMap5);
            Map<String, Object> resultMap6 = Maps.newHashMap();
            resultMap6.put("name", "不合格数");
            resultMap6.put("amount", thisUnqualifiedQuantity);
            resultMap6.put("yoy", yoyUnqualifiedQuantity);
            resultMap6.put("qoq", qoqUnqualifiedQuantity);
            resultList.add(5, resultMap6);
            return Response.ok(resultList);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    @OpenMethod(
            key = "web.breed.report.whole.info",
            httpMethods = RequestMethod.GET
    )
    public Response<List<Map<String , Object>>> breedReportWholeInfo(){

        try{
            Map<String, Object> map = buildDataParamMap(null, null);
            BigDecimal defaultValue = new BigDecimal(0.00);
            Calendar calendar = Calendar.getInstance();
            map.put("year",calendar.get(Calendar.YEAR));
            map.put("month",calendar.get(Calendar.MONTH) + 1);
            List<Map<String, Object>> thisResultPre = djtBreedReportsReadService.findSumByIsToLocalAndMonth(map);
            Double thisIsLocal = 0.00;
            Double thisNoIsLocal = 0.00;
            for (Map<String, Object> map1 : thisResultPre)
                if ((int) map1.get("isToLocal") == -1)
                    thisNoIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
                else thisIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();

            Map<String, Object> thisYearOtherDataMap = djtBreedReportsReadService.findSumForWebDataAnalysisAndMonth(map);
            Double thisQualifiedQuantity = thisYearOtherDataMap != null ? ((BigDecimal) thisYearOtherDataMap.getOrDefault("qualifiedQuantity", defaultValue)).doubleValue() : 0.00;
            Double thisUnqualifiedQuantity = thisYearOtherDataMap != null ? ((BigDecimal) thisYearOtherDataMap.getOrDefault("unqualifiedQuantity", defaultValue)).doubleValue() : 0.00;


            map.put("month",calendar.get(Calendar.MONTH));
            List<Map<String, Object>> lastYearResultPre = djtBreedReportsReadService.findSumByIsToLocalAndMonth(map);
            Double lastYearIsLocal = 0.00;
            Double lastYearNoIsLocal = 0.00;
            for (Map<String, Object> map1 : lastYearResultPre)
                if ((int) map1.get("isToLocal") == -1)
                    lastYearNoIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
                else lastYearIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
            Map<String, Object> lastYearOtherDataMap = djtBreedReportsReadService.findSumForWebDataAnalysisAndMonth(map);
            Double lastYearQualifiedQuantity = lastYearOtherDataMap != null ? ((BigDecimal) lastYearOtherDataMap.getOrDefault("qualifiedQuantity", defaultValue)).doubleValue() : 0.00;
            Double lastYearUnqualifiedQuantity = lastYearOtherDataMap != null ? ((BigDecimal) lastYearOtherDataMap.getOrDefault("unqualifiedQuantity", defaultValue)).doubleValue() : 0.00;

            map.put("year",calendar.get(Calendar.YEAR) - 1);
            map.put("month",calendar.get(Calendar.MONTH) + 1);
            List<Map<String, Object>> lastMonthResultPre = djtBreedReportsReadService.findSumByIsToLocalAndMonth(map);
            Double lastMonthIsLocal = 0.00;
            Double lastMonthNoIsLocal = 0.00;
            for (Map<String, Object> map1 : lastMonthResultPre)
                if ((int) map1.get("isToLocal") == -1)
                    lastMonthIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
                else lastMonthNoIsLocal += ((BigDecimal) map1.get("quantity")).doubleValue();
            Map<String, Object> lastMonthOtherDataMap = djtBreedReportsReadService.findSumForWebDataAnalysisAndMonth(map);
            Double lastMonthQualifiedQuantity = lastMonthOtherDataMap != null ? ((BigDecimal) lastMonthOtherDataMap.getOrDefault("qualifiedQuantity", defaultValue)).doubleValue() : 0.00;
            Double lastMonthUnqualifiedQuantity = lastMonthOtherDataMap != null ?  ((BigDecimal) lastMonthOtherDataMap.getOrDefault("unqualifiedQuantity", defaultValue)).doubleValue() : 0.00;

            DecimalFormat df = new DecimalFormat("######0.00");
            String yoyQualifiedQuantity = lastYearQualifiedQuantity == 0.00 ? thisQualifiedQuantity * 100 + "%" : df.format((thisQualifiedQuantity / lastYearQualifiedQuantity - 1) * 100) + "%";
            String yoyUnqualifiedQuantity = lastYearUnqualifiedQuantity == 0.00 ? thisUnqualifiedQuantity * 100 + "%" : df.format((thisUnqualifiedQuantity / lastYearUnqualifiedQuantity - 1) * 100) + "%";
            String yoyIsLocal = lastYearIsLocal == 0.00 ? thisIsLocal * 100 + "%" : df.format((thisIsLocal / lastYearIsLocal - 1) * 100) + "%";
            String yoyNoIsLocal = lastYearNoIsLocal == 0.00 ? thisNoIsLocal * 100 + "%" : df.format((thisNoIsLocal / lastYearNoIsLocal - 1) * 100) + "%";

            String qoqQualifiedQuantity = lastMonthQualifiedQuantity == 0.00 ? thisQualifiedQuantity * 100 + "%" : df.format((thisQualifiedQuantity / lastMonthQualifiedQuantity - 1) * 100) + "%";
            String qoqUnqualifiedQuantity = lastMonthUnqualifiedQuantity == 0.00 ? thisUnqualifiedQuantity * 100 + "%" : df.format((thisUnqualifiedQuantity / lastMonthUnqualifiedQuantity - 1) * 100) + "%";
            String qoqIsLocal = lastMonthIsLocal == 0.00 ? thisIsLocal * 100 + "%" : df.format((thisIsLocal / lastMonthIsLocal - 1) * 100) + "%";
            String qoqNoIsLocal = lastMonthNoIsLocal == 0.00 ? thisNoIsLocal * 100 + "%" : df.format((thisNoIsLocal / lastMonthNoIsLocal - 1) * 100) + "%";

            Double sum = thisQualifiedQuantity + thisUnqualifiedQuantity;

            String gdpQualifiedQuantity = sum == 0.00 ? thisQualifiedQuantity * 100 + "%" : df.format((thisQualifiedQuantity / sum) * 100) + "%";
            String gdpUnqualifiedQuantity = sum == 0.00 ? thisUnqualifiedQuantity * 100 + "%" : df.format((thisUnqualifiedQuantity / sum) * 100) + "%";
            String gdpIsLocal = sum == 0.00 ? thisIsLocal * 100 + "%" : df.format((thisIsLocal / sum) * 100) + "%";
            String gdpNoIsLocal = sum == 0.00 ? thisNoIsLocal * 100 + "%" : df.format((thisNoIsLocal / sum) * 100) + "%";

            List<Map<String, Object>> resultList = new ArrayList<>();
            Map<String, Object> resultMap1 = Maps.newHashMap();
            resultMap1.put("name", "本地屠宰");
            resultMap1.put("amount", thisIsLocal);
            resultMap1.put("yoy", yoyIsLocal);
            resultMap1.put("qoq", qoqIsLocal);
            resultMap1.put("gdp", gdpIsLocal);
            resultList.add(0, resultMap1);
            Map<String, Object> resultMap2 = Maps.newHashMap();
            resultMap2.put("name", "销往外地");
            resultMap2.put("amount", thisNoIsLocal);
            resultMap2.put("yoy", yoyNoIsLocal);
            resultMap2.put("qoq", qoqNoIsLocal);
            resultMap2.put("gdp", gdpNoIsLocal);
            resultList.add(1, resultMap2);
            Map<String, Object> resultMap3 = Maps.newHashMap();
            resultMap3.put("name", "合格数");
            resultMap3.put("amount", thisQualifiedQuantity);
            resultMap3.put("yoy", yoyQualifiedQuantity);
            resultMap3.put("qoq", qoqQualifiedQuantity);
            resultMap3.put("gdp", gdpQualifiedQuantity);
            resultList.add(2, resultMap3);
            Map<String, Object> resultMap4 = Maps.newHashMap();
            resultMap4.put("name", "不合格数");
            resultMap4.put("amount", thisUnqualifiedQuantity);
            resultMap4.put("yoy", yoyUnqualifiedQuantity);
            resultMap4.put("qoq", qoqUnqualifiedQuantity);
            resultMap4.put("gdp", gdpUnqualifiedQuantity);
            resultList.add(3, resultMap4);

            return Response.ok(resultList);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    @OpenMethod(
            key = "web.find.breed.report.sum.total.count.and.quantity",
            httpMethods = RequestMethod.GET
    )
    public Response<Map<String , Object>> findSum(){
        try{
            return Response.ok(djtBreedReportsReadService.selectSum(buildDataParamMap(null, null)));
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(e.getMessage());
        }

    }


    /**
     * 清除耳标的参数
     *
     * @param earTagNumbers 耳标list
     * @return Map<String , Object>
     */
    private Map<String, Object> clearEarIsSelectedParam(List<String> earTagNumbers) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("earTagNumbers", earTagNumbers);
        map.put("isSelected", 1);
        map.put("status", 2);

        return map;
    }

    /**
     * 单据耳标的list的参数
     *
     * @param reportId 单据id
     * @return Map<String,Object>
     */
    private Map<String, Object> getParamMapOfEarLifeQuery(Long reportId, Integer reportType) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("reportId", reportId);
        map.put("reportType", reportType);
        return map;
    }

    /**
     * 无害化删除的参数
     *
     * @param reportId   关联单据id
     * @param reportType 关联单据类型
     * @return Map<String , Object>
     */
    private Map<String, Object> getUpdateHarmlessParamMap(Long reportId, Integer reportType) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("reportId", reportId);
        map.put("reportType", reportType);
        return map;
    }

    /**
     * 生产记录删除的参数
     *
     * @param reportId   关联单据id
     * @param reportType 关联单据类型
     * @return
     */
    private Map<String, Object> getParamMapOfUpdateProduction(Long reportId, Integer reportType) {
        Map<String, Object> map = Maps.newHashMap();
        map.put("reportId", reportId);
        map.put("reportType", reportType);

        return map;
    }

    /**
     * 恢复存栏的参数
     *
     * @param id 产地检疫单据对象id
     * @return Map<String , Object>
     */
    private Map<String, Object> getStockUpdateParamsMap(Long id) {
        DjtBreedReports djtBreedReports = djtBreedReportsReadService.findById(id);
        Map<String, Object> stockUpdateParamsMap = Maps.newHashMap();
        stockUpdateParamsMap.put("farmId", djtBreedReports.getFarm_id());
        stockUpdateParamsMap.put("changeQuantity", 0 - djtBreedReports.getQuantity());
        return stockUpdateParamsMap;
    }

    private Map<String, Object> buildDataParamMap(List<Integer> areaList,
                                                  List<Integer> breedType) {

        List<Long> farmsIds = new ArrayList<>();
        farmsIds.add(-1L);
        if (areaList == null || areaList.isEmpty()) {
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            List<Farms> farmsList = farmsService.selectByUserId(loginInfo.getId());
            for (Farms farms : farmsList) farmsIds.add(farms.getId());
        } else {
            Map<String, Object> map = Maps.newHashMap();
            int i = 0;
            for (Integer areaCode : areaList) {
                if (i == 0) {
                    map.put("province_id", areaCode);
                } else if (i == 1) {
                    map.put("city_id", areaCode);
                } else if (i == 2) {
                    map.put("region_id", areaCode);
                } else if (i == 3) {
                    map.put("street_id", areaCode);
                }
                i++;
            }
            List<Farms> farmsList = farmsService.selectByMap(map);
            for (Farms farms : farmsList) farmsIds.add(farms.getId());
        }
        Map<String, Object> map = Maps.newHashMap();
        if (breedType != null && breedType.size() > 0) {
            switch (breedType.size()) {
                case 1:
                    map.put("breedType", breedType.get(0));
                    break;
                case 2:
                    map.put("breedSecondType", breedType.get(1));
                    break;
                case 3:
                    map.put("breedThirdType", breedType.get(2));
                default:
                    break;
            }
        }
        map.put("farmsIds", farmsIds);
        map.put("deleteFlag", 1);
        return map;

    }


    private Date getLastYearThisTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH);
        Integer day = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.set(year - 1, month, day);

        return calendar.getTime();
    }

    private Date getLastMonthThisTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH);
        Integer day = calendar.get(Calendar.DAY_OF_MONTH);

        calendar.set(year, month - 1, day);

        return calendar.getTime();
    }
}
